package net.vengeancecraft.NoPortals;

import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import ru.tehkode.permissions.PermissionManager;
import ru.tehkode.permissions.bukkit.PermissionsEx;


public class NoPortals extends JavaPlugin
{
    public NoPortals plugin;
    private FileHandler eLogger = new FileHandler();
    private final NoPortalsPlayerListener plistener = new NoPortalsPlayerListener(this);
    private final WorldEvents wevents = new WorldEvents();
    public static PermissionManager pex;
    public static boolean togglePortals = false;
    public static boolean watchDog = false;
    public static boolean destroyer = false;
    public static boolean stopEnder = false;
    public static boolean toggleCustomMessage = false;
    public static String customMessage = "You do not have permission to create a portal.";
    public static final Logger log = Logger.getLogger("Minecraft");
    public static HashMap<String, Boolean> validPortals = new HashMap<String, Boolean>();
    
    
    public NoPortals()
    {
       
    }
 
    private void setupPermissions()
    {
        Plugin permissionsPlugin = getServer().getPluginManager().getPlugin("PermissionsEx");
        if(pex == null)
        {
            if(permissionsPlugin != null)
            {
                pex  = PermissionsEx.getPermissionManager();
                 log.info("[" + this.getDescription().getName() + "] Found and will use " + permissionsPlugin.getDescription().getFullName()+ " for permissions.");
            } 
            else
            {
                log.info("[" + this.getDescription().getName() + "] Permissions plugin not detected, defaulting to OP."); 
                
            }
        }
    }

    
    @Override
    public void onEnable()
    {
       String result  = "";
        boolean loadresult = load();
        if(loadresult)
        {
            log.info("[" +this.getDescription().getName() + "] Config loaded successfully.");
        }
        loadHashes();
        getServer().getPluginManager().registerEvents(plistener, this);
        getServer().getPluginManager().registerEvents(wevents, this);
        
           
        setupPermissions();
               
        result  = (watchDog == true) ? "enabled." : "disabled.";
        log.info("[" + this.getDescription().getName() + "] Watchdog is " + result);
     
        if(watchDog == true)
        {
            result  = (destroyer == true) ? "enabled." : "disabled.";
            log.info("[" + this.getDescription().getName() + "] Destroyer is " + result);
        }
        
        result  = (stopEnder == true) ? "enabled." : "disabled.";
        log.info("[" + this.getDescription().getName() + "] StopEnder is " + result);
      
        result = (toggleCustomMessage == true) ? "enabled." : "disabled.";
        log.info("[" + this.getDescription().getName() + "] Custom Messages are " + result);
    }

    @Override
    public void onDisable()
    {
       if(plugin != null)
       {
           getServer().getScheduler().cancelTasks(plugin);
       }
       
    }
    
    public static boolean hasPerm(CommandSender sender, String permNode)
    {
       
        if (NoPortals.pex == null || !(sender instanceof Player)) 
        {
            return sender.isOp() || sender.hasPermission(permNode);
        }
	else
        {
            Player player = (Player)sender;
            return NoPortals.pex.has(player, permNode); 
        }
    }
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
    {
        if(commandLabel.equalsIgnoreCase("noportals"))
        {
           if(hasPerm(sender,"noportals.reload"))
           {
                boolean loadresult = load();
                validPortals.clear();
                loadHashes();
                if (loadresult)
                {
                   sender.sendMessage("NoPortal config reloaded successfully.");
                   log.info("[" + this.getDescription().getName() + "] Config reloaded successfully."); 
                   
                }
                else
                {
                   sender.sendMessage("[" + this.getDescription().getName() + "] Error loading config.");
                   
                }  
            }
            return true;
        }
         
        return false;
       
       
    }

    public void loadHashes()
    {
        try
        {
            eLogger.loadPortalsFromFile("ValidPortals");
        }
        catch (IOException ex)
        {
            Logger.getLogger(NoPortals.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        try
        {
            eLogger.loadPortalsFromFile("Portals");
        }
        catch (IOException ex)
        {
            Logger.getLogger(NoPortals.class.getName()).log(Level.SEVERE, null, ex);
        }    
    
    }
    
    public boolean load()
    {
       boolean flagchange = false;
       FileConfiguration config;
      
       try
       {
            config = getConfig();
                                  
            if(!config.contains("watchdog"))
            {
                config.set("watchdog", false);
                flagchange = true;
            }
            else
            {
                 watchDog = config.getBoolean("watchdog", false);
            }
            
            if(!config.contains("destroyer"))
            {
                config.set("destroyer", false);
                flagchange = true;
            }
            else
            {
                destroyer = config.getBoolean("destroyer", false);
            }
            
            if(!config.contains("stopEnder"))
            {
                config.set("stopEnder", false);
                flagchange  = true;
            }
            else
            {
                stopEnder = config.getBoolean("stopEnder", false);
            }
           
            if(!config.contains("toggleCustomMessage"))
            {
                config.set("toggleCustomMessage", false);
                flagchange = true;
            }
            else
            {
                toggleCustomMessage = config.getBoolean("toggleCustomMessage", false);
            }
            
            if(!config.contains("customMessage"))
            {
                config.set("customMessage", customMessage.toString());
                flagchange = true;
            }
            else
            {
                customMessage = config.getString("customMessage", customMessage.toString());
            }
            
            if(flagchange)
            {
                saveConfig();
            }
            return true;
       }
       catch(Exception ex)
       {
           Logger.getLogger(NoPortals.class.getName()).log(Level.SEVERE, null, ex);
           return false;
       }

       
    }
}
